package com.ruoyi.common.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.TextStyle;
import java.util.*;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DayUtils extends org.apache.commons.lang3.time.DateUtils
{
    private static transient int gregorianCutoverYear = 1582;
    /** 闰年中每月天数 */
    private static final int[] DAYS_P_MONTH_LY= {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    /** 非闰年中每月天数 */
    private static final int[] DAYS_P_MONTH_CY= {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    public static final String SHORT_DATE_FORMAT = "yyyy-MM-dd";

    /** 代表数组里的年、月、日 */
    private static final int Y = 0, M = 1, D = 2;



    /**
     * 以循环的方式计算日期
     * @param beginDate endDate
     * @param
     * @return
     */
    public static List<String> getEveryday(String beginDate , String endDate){
        if (StringUtils.isEmpty(endDate)){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            endDate = simpleDateFormat.format(date);
        }
        long days = countDay(beginDate, endDate);
        int[] ymd = splitYMD( beginDate );
        List<String> everyDays = new ArrayList<String>();
        everyDays.add(beginDate);
        for(int i = 0; i < days; i++){
            ymd = addOneDay(ymd[Y], ymd[M], ymd[D]);
            everyDays.add(formatYear(ymd[Y])+"-"+formatMonthDay(ymd[M])+"-"+formatMonthDay(ymd[D]));
        }
        return everyDays;
    }

    /**
     * 获取两个日期之间的所有年
     *
     * @param startTime
     * @param endTime
     * @return：list
     */
    public static List<String> getYearBetweenDate(String startTime, String endTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        // 声明保存日期集合
        List<String> list = new ArrayList<>();
        try {
            // 转化成日期类型
            Date startDate = sdf.parse(startTime);
            Date endDate = sdf.parse(endTime);

            //用Calendar 进行日期比较判断
            Calendar calendar = Calendar.getInstance();
            while (startDate.getTime() <= endDate.getTime()) {

                // 把日期添加到集合
                list.add(sdf.format(startDate));

                // 设置日期
                calendar.setTime(startDate);

                //把年数增加 1
                calendar.add(Calendar.YEAR, 1);

                // 获取增加后的日期
                startDate = calendar.getTime();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
    /**
     * 计算两个日期之间相隔的天数
     * @param begin
     * @param end
     * @return
     * @throws ParseException
     */
    public static long countDay(String begin,String end){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date beginDate , endDate;
        long day = 0;
        try {
            beginDate= format.parse(begin);
            endDate= format.parse(end);
            day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return day;
    }

    /**
     * 将代表日期的字符串分割为代表年月日的整形数组
     * @param date
     * @return
     */
    public static int[] splitYMD(String date){
        date = date.replace("-", "");
        int[] ymd = {0, 0, 0};
        ymd[Y] = Integer.parseInt(date.substring(0, 4));
        ymd[M] = Integer.parseInt(date.substring(4, 6));
        ymd[D] = Integer.parseInt(date.substring(6, 8));
        return ymd;
    }


    /**
     * 日期加1天
     * @param year
     * @param month
     * @param day
     * @return
     */
    private static int[] addOneDay(int year, int month, int day){
        if(isLeapYear( year )){
            day++;
            if( day > DAYS_P_MONTH_LY[month -1 ] ){
                month++;
                if(month > 12){
                    year++;
                    month = 1;
                }
                day = 1;
            }
        }else{
            day++;
            if( day > DAYS_P_MONTH_CY[month -1 ] ){
                month++;
                if(month > 12){
                    year++;
                    month = 1;
                }
                day = 1;
            }
        }
        int[] ymd = {year, month, day};
        return ymd;
    }


    /**
     * 检查传入的参数代表的年份是否为闰年
     * @param year
     * @return
     */
    public static boolean isLeapYear(int year) {
        return year >= gregorianCutoverYear ?
                ((year%4 == 0) && ((year%100 != 0) || (year%400 == 0))) : (year%4 == 0);
    }

    /**
     * 将不足四位的年份补足为四位
     * @param decimal
     * @return
     */
    public static String formatYear(int decimal){
        DecimalFormat df = new DecimalFormat("0000");
        return df.format( decimal );
    }

    /**
     * 将不足两位的月份或日期补足为两位
     * @param decimal
     * @return
     */
    public static String formatMonthDay(int decimal){
        DecimalFormat df = new DecimalFormat("00");
        return df.format( decimal );
    }

    public static Integer typeSort(String type){
        String substring = type.substring(0, 1);
        if(substring.equalsIgnoreCase("N")){
            return 1;
        }
        if(substring.equalsIgnoreCase("D")){
            return 2;
        }
        if(substring.equalsIgnoreCase("T")){
            return 3;
        }
        if(substring.equalsIgnoreCase("C")){
            return 4;
        }
        if(substring.equalsIgnoreCase("M")){
            return 5;
        }
        return 6;
    }

    public  static List<Map<String,String>> getCycleList(int cycleNum,String startTime,String endTime) throws ParseException {
        System.out.println("统计的时间段为：从"+startTime+"到"+endTime);
        Date endParse = new SimpleDateFormat("yyyy-MM-dd").parse(endTime);
        Long endLong = endParse.getTime();

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//这个是你要转成后的时间的格式
        endTime = sdf.format(new Date(endLong));
        System.out.println("结束时间是："+endTime);

        int daysBetweenNum = daysBetween(startTime, endTime);
        int cycleForNum = daysBetweenNum % cycleNum == 0 ? (daysBetweenNum / cycleNum) : (daysBetweenNum / cycleNum) + 1;
        System.out.println("两日期间相隔的天数为：" + daysBetweenNum);
        System.out.println("周期选择是：" + cycleNum + "天一周期, 则切割出来的周期存在个数：" + cycleForNum);
        Date startParse = new SimpleDateFormat("yyyy-MM-dd").parse(startTime);
        Long startLong = startParse.getTime();

        Long calculationLong = startLong;

        List<Map<String,String>> CycleTimeList=new ArrayList();
        for (int i = 1; i <= cycleForNum; i++) {

            String startStr = sdf.format(new Date(calculationLong));
            Date startStrParse = new SimpleDateFormat("yyyy-MM-dd").parse(startStr);
            Long startStrLong = startStrParse.getTime();
            Long cycleLong = cycleNum*86400000l;
            calculationLong = startStrLong + cycleLong;
            String endStr = endTime;
            if (calculationLong <= endLong) {
                endStr = sdf.format(new Date(calculationLong));
            }
            System.out.println("起始:" + startStr + "结束：" + endStr);
            calculationLong = calculationLong+86400000l;
            HashMap<String, String> stringStringHashMap = new HashMap<>();
            stringStringHashMap.put("startStr",startStr);
            stringStringHashMap.put("endStr",endStr);
            stringStringHashMap.put("stor",String.valueOf(i));
            CycleTimeList.add(stringStringHashMap);
        }
        Collections.sort(CycleTimeList, new Comparator<Map<String,String>>() {
            @Override
            public int compare(Map<String,String> o1, Map<String,String> o2) {
                return o2.get("stor").compareTo(o1.get("stor"));
            }

            @Override
            public boolean equals(Object obj) {
                return false;
            }
        });
        System.out.println("周期list："+CycleTimeList.toString());
        return CycleTimeList;
    }

    public static int daysBetween(String smdate, String bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

}
